//
//  LSZEmoticonToolBar.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/19.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit

//定义按钮的枚举
enum LSZEmoticonToolBarButtonType: Int {
//    默认
    case Normal = 0
//    Emoji
    case Emoji = 1
//    浪小花
    case Lxh = 2
}

//表情视图的toolBar
class LSZEmoticonToolBar: UIStackView {
    
//    记录上次选中的按钮
    var lastSelectedButton: UIButton?
//    定义选中toolbar按钮的闭包
    var selectedToolBarButtonClosure: ((type: LSZEmoticonToolBarButtonType) -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
//        设置布局方式
        axis = .Horizontal
//        设置子控件的填充方式
        distribution = .FillEqually
        
        addChildButton("默认", imageName: "compose_emotion_table_left", type: .Normal)
        addChildButton("Emoji", imageName: "compose_emotion_table_mid", type: .Emoji)
        addChildButton("浪小花", imageName: "compose_emotion_table_right", type: .Lxh)
    }
    
//    创建子控件的通用方法
    private func addChildButton(title: String, imageName: String, type: LSZEmoticonToolBarButtonType) {
        let button = UIButton()
//        设置tag值等于枚举的原始值
        button.tag = type.rawValue
//        添加点击事件
        button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
//        设置文字及其颜色
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
//        设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
//        设置背景图片
        button.setBackgroundImage(UIImage(named: imageName + "_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: imageName + "_selected"), forState: .Selected)
//        取消高亮
        button.adjustsImageWhenHighlighted = false
        addArrangedSubview(button)
    }
 
    
    // MARK: 按钮的点击事件
   @objc private func buttonAction(button: UIButton) {
//        判断是否是同一个按钮
        if lastSelectedButton == button {
            return
        }
        
//        清除上一个按钮
        lastSelectedButton?.selected = false
        button.selected = true
//        设置为这次点击的按钮
        lastSelectedButton = button
   
        
        
//        通过tag值获取枚举类型
        let type = LSZEmoticonToolBarButtonType(rawValue: button.tag)!
        
//        执行闭包回调
        selectedToolBarButtonClosure?(type: type)
        
    }

}
